﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Threading;
using System.Net;
using System.Diagnostics;

namespace Mongaba.Core.Listeners
{
    internal class CoordinatorListener
    {
        static byte[] buf = new byte[65000];
        static void Receive(IAsyncResult ar)
        {
            try
            {
                Socket listener = ar.AsyncState as Socket;
                int bytesReceived = listener.EndReceive(ar);
                string str = Encoding.ASCII.GetString(buf, 0, bytesReceived);
                IPAddress ip = IPAddress.Parse(str);
                string strMessage = Utilities.HostIp.ToString();
                byte[] data = Encoding.ASCII.GetBytes(strMessage);
                WaitForData();
                try
                {
                    Socket sckResponse = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

                    sckResponse.Connect(new IPEndPoint(ip, Utilities.ProcessResponseListenerPort));

                    sckResponse.Send(data);

                    sckResponse.Close();
                }
                finally
                {
                    WaitForData();
                }
            }
            catch (ObjectDisposedException)
            {
                return;
            }
            

        }
        static void WaitForData()
        {

            try
            {
                sckListenter.BeginReceive(buf, 0, buf.Length, SocketFlags.None, new AsyncCallback(Receive), sckListenter);
            }            
            catch (ObjectDisposedException)
            {
                return;
            }
            catch (NullReferenceException)
            {
                return;
            }
        }
               
        static Socket sckListenter;
        /// <summary>
        /// Inicia o processo de escuta de IPs na porta definida em Mongaba.Utilities.CoordinatorRequestListenerPort
        /// </summary>
        public static void Start()
        {
            sckListenter = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            sckListenter.Bind(new IPEndPoint(IPAddress.Any, Utilities.CoordinatorRequestListenerPort));
            _isListening = true;
            WaitForData();
            Console.WriteLine("Escuta do coordenador começou.");

        }

        /// <summary>
        /// Termina o serviço de escuta na porta definida em Mongaba.Utilities.CoordinatorRequestListenerPort
        /// </summary>
        public static void Stop()
        {
            if (sckListenter != null)
            {

                sckListenter.Close(1);
                sckListenter = null;
               _isListening = false;
                Console.WriteLine("Escuta do coordenador terminada.");
            }
        }

        static bool _isListening = false;
        public static bool IsListening
        {
            get { return _isListening; }
        }



    }
}
